package com.swak.excel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * Excel 随机写数据
 * 
 * @author 618lf
 */
public class RandomWrite {

	public static void main(String[] args) throws IOException {
		FileOutputStream out = new FileOutputStream("D:\\ElectroBill_out.xlsx");
		FileInputStream is = new FileInputStream("D:\\ElectroBill.xlsx");
		Workbook template = ExcelUtils.load(is);

		/*
		 * 随机读写的数据
		 */
		RandomSheet sheet = RandomSheet.of();
		sheet.add(RandomData.of().setRow(1).setCell(2).setValue("测试月份"));

		write(template, sheet);

		template.write(out);
	}

	private static void write(Workbook template, RandomSheet data) {
		Sheet sheet = template.getSheetAt(data.getIndex());
		if (sheet == null) {
			return;
		}

		List<RandomData> datas = data.getDatas();
		for (RandomData rd : datas) {
			Row row = sheet.getRow(rd.getRow());
			if (row == null) {
				row = sheet.createRow(rd.getRow());
			}
			Cell cell = row.getCell(rd.getCell());
			if (cell == null) {
				cell = row.createCell(rd.getCell());
			}
			CellType type = cell.getCellType();
			if (type == CellType.NUMERIC) {
				cell.setCellValue(Double.parseDouble(rd.getValue()));
			} else {
				cell.setCellValue(rd.getValue());
			}
		}
	}
}
